export default {
  lockReconnect: false, //避免重连
  timer: null,
  timeoutObj: null,
  timeout: 20000, //20秒一次心跳
  ws: null, //定义websocket
  serverTimeoutObj: null,
  sendInfor: "ping",

  //建立ws
  initSocket: function() {
    let token = localStorage.getItem("token");
    this.ws = new WebSocket(`wss://api.laismell.com//laiwen/wsserver/${token}`);
    // 测试环境
    // this.ws = new WebSocket(`wss://api-laiwen.inahara.top/laiwen/wsserver/${token}`);
    this.initEventHandle(this.ws);
  },
  //处理webSocket
  initEventHandle: function(ws) {
    //连接关闭时触发
    (ws.onclose = (res) => {
      let token = localStorage.getItem("token");
      if (token) {
        //重连方法
        this.reconnect();
      }
    }),
      //连接建立时触发
      (ws.onopen = () => {
        //心跳检测重置
        this.start();
      }),
      //收到消息
      (ws.onmessage = ({ data }) => {
        if (data == "消息接受成功" || data == "连接成功") {
          this.reset();
        }
      });
  },
  //断线重连
  reconnect: function() {
    console.log("重新连接");
    if (this.lockReconnect) return;
    this.lockReconnect = true;
    //清除计时器
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      //重连
      this.initSocket();
      this.lockReconnect = false;
    }, 5000);
  },
  //开启心跳
  start: function() {
    let that = this;
    that.timeoutObj = setTimeout(() => {
      console.log(`发送${that.sendInfor}`);
      that.ws.send(that.sendInfor);
      that.serverTimeoutObj = setTimeout(() => {
        that.ws.close();
      }, that.timeout);
    }, that.timeout);
  },
  //重置心跳
  reset: function() {
    let that = this;
    clearTimeout(that.timeoutObj);
    clearTimeout(that.serverTimeoutObj);
    console.log("重置了心跳");
    //重启心跳
    that.start();
  },
};
